function mle = SMLE_v2(params,data,random_draws, num_drugs, num_periods, id, outside, S)
%SMLE Computes likelihood function given data and parameter guess

    delta = params(1:4);
    
    alpha = params(5);
    % flatten and make it easier to evaluate in cases with no incumbent
    gamma = [params(6:9);params(10:13);params(14:17);params(18:21);0;0;0;0];
    sigma = params(22);
    
    random_draws = random_draws * sigma;
    
    % for readability
    drugid = data(:,3); % current drug id
    incumbent_id = data(:,6);
    incumbent_id(isnan(incumbent_id)) = num_drugs + 1; % CHANGED
    
    % STEP 1: transform data into ID, quarter u_ij based on parameters
    % Basic_part: drug quality - alpha * copay
    % NEW: data(6) marks the incumbent; apply gamma, then see if it is
    % actually the incumbent
    u = delta(data(:,3)) - ...
        alpha * data(:,5) + gamma(incumbent_id + num_drugs * (drugid-1)); % gamma matrix evaluated against two column vectors
    
    % repmat sideways and add random draw rows
    u = repmat(u,1,S) + random_draws(data(:,3) + num_drugs * (data(:,1) - 1), :);
    
    % STEP 2: aggregate and compute SMLE
    eu = exp(u);
    probs = zeros(size(outside,1),S);
    
    for i=1:S
        groupsum = 1 + accumarray(id, eu(:,i));
        eu_chosen = eu(:,i) .* data(:,4);
        chosen_sum = accumarray(id,eu_chosen);
        p = ((1 - outside) .* chosen_sum + outside * 1) ./ groupsum;
        
        probs(:,i) = p;
    end

    
    mean_probs= mean(probs,2);
    mle = sum(log(mean_probs));
end

